<?php
/**
 * @author spenceryg
 * @date 2023/6/24
 * @time 12:13 上午
 * @focus love & life
 */


namespace app\api1\controller;


use app\common\lib\WxTemplateMsg;
use app\common\model\GptToken;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response;
use app\common\model\RobotFiles;
use hg\apidoc\annotation as Apidoc;


class Cron extends \app\BaseController
{
    /**
     * doEmbedding
     * @Apidoc\Title("训练")
     */
    public function doEmbedding(): \think\response\Json
    {
        $success = 0;
        $fail = 0;
        $all = 0;
        $ids = RobotFiles::where('is_train', 0)
            ->where('robot_id', 15)
            ->limit(1)->column('id');
        $all = count($ids);
        $client = new \GuzzleHttp\Client(
            [
                'base_uri' => config('transfer.transit_address'),
                'timeout' => 180,
            ]
        );
        if($ids){
            $requests_fun = function ($ids) use ($client) {
                foreach ($ids as $id) {
                    yield function () use ($client, $id) {
                        $robotFile = \app\common\model\RobotFiles::find($id);
                        $gptToken = GptToken::order('update_time desc')->find();
                        $gptToken->force(true)->save();
                        $openai_api_key = $gptToken['token'];
                        $json = [];
                        $json['openai_api_key'] = $openai_api_key;
                        $json['filename'] = $robotFile['name'];
                        $json['file_id'] = $robotFile['id'];
                        $json['persist_directory'] = 'dir_' .  $robotFile['robot_id'];
                        return $client->postAsync('/embedding_one',['json' => $json]);
                    };
                }
            };
            $pool = new Pool($client, $requests_fun($ids), [
                'concurrency' => 50,
                'fulfilled' => function (Response $response)  use (&$success) {
                    $body = $response->getBody()->getContents();
                    $data = json_decode($body, true);
                    $robotFile = \app\common\model\RobotFiles::find($data['file_id']);
                    $robotFile->is_train = 1;
                    $robotFile->number_of_documents = $data['length'];
                    $robotFile->save();
                    $success++;
                },
                'rejected' => function (RequestException $reason, $index) use (&$fail) {
                    $fail++;
                },
            ]);


            $promise = $pool->promise();
            $promise->wait();

        }
        return success('训练成功', ['success' => $success, 'fail' => $fail, 'all' => $all]);
    }


    /**
     * @Apidoc\Title("机器人套餐到期模版消息提醒")
     */
    public function TemplateMsgForNotifyRenew()
    {
        $robots = \app\common\model\Robot::select();
        foreach ($robots as $robot) {
            $end_time = $robot['expiration_time'];
            $daysDifference = floor($end_time - time() / (60 * 60 * 24));
            if(in_array($daysDifference, [30, 10, 1])){
                WxTemplateMsg::send($robot['member_id'], 5, [
                    'thing44' => 'ChatAI到期提醒',
                    'thing36' => $robot->robotProducts->name.'套餐',
                    'time18' => date('Y-m-d', $end_time),
                ]);
            }
        }
        return 'success';

    }

    /**
     * @Apidoc\Title("机器人套餐-字数超出限制-模版消息提醒")
     * @Apidoc\Param ("robot_id", type="int", default="1", desc="机器人id")
     */
    public function TemplateMsgForOutOfLimit(){
        $robot_id = input('robot_id',0,'intval');
        $robot = \app\common\model\Robot::find($robot_id);
        WxTemplateMsg::send($robot['member_id'], 4, [
            'thing44' => 'ChatAI套餐超出提醒',
            'thing36' => $robot['name'].'(机器人id:'.$robot['id'].')',
            'thing35' => '知识库字数超出套餐限制，请升级套餐。'
        ]);
        return 'success';
    }
}
